//
//  ApiRequestUtil.m
//  CCApp
//
//  Created by CC on 2019/6/1.
//  Copyright © 2019 Shanghai YingXiang Network Technology Co., Ltd. All rights reserved.
//

#import "ApiRequestUtil.h"
#import "LcFoundation.h"
#import "LcLoadingIndicatorView.h"
#import "NetWorkRequestGroup.h"
#import "CCRequestData.h"
#import "CCResponseData.h"
#import "UserManager.h"
#import "YYModel.h"

static NetWorkRequestGroup* requestGroup;

@implementation ApiRequestUtil

+ (void)initialize {
  if (self == [ApiRequestUtil self]) {
    requestGroup = [[NetWorkRequestGroup alloc] init];
  }
}

+ (void)sendRequest:(CCRequestData*)requestData
           successHandler:(CKSuccessHandler)successHandler
             errorHandler:(CKApiErrorHandler)errorHandler
showModalLoadingIndicator:(BOOL)showModalLoadingIndicator {
  if (showModalLoadingIndicator) {
    if ([NSThread isMainThread]) {
      [LcLoadingIndicatorView showModal];
    } else {
      [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [LcLoadingIndicatorView showModal];
      }];
    }
  }
  NSString* urlString = [requestData urlString];
  NSDictionary* parameters = [requestData yy_modelToJSONObject];
  [requestGroup POST:urlString parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
    if (showModalLoadingIndicator) {
      if ([NSThread isMainThread]) {
        [LcLoadingIndicatorView hideModal];
      } else {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
          [LcLoadingIndicatorView hideModal];
        }];
      }
    }
    Class responseClass = [requestData responseClass];
    CCResponseData* responseData = [responseClass yy_modelWithDictionary:responseObject];
    successHandler(requestData, responseData);
  } failure:^(NSURLSessionDataTask *task, NSError *error) {
    if (showModalLoadingIndicator) {
      if ([NSThread isMainThread]) {
        [LcLoadingIndicatorView hideModal];
      } else {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
          [LcLoadingIndicatorView hideModal];
        }];
      }
    }
    LcApiError* apiError = [LcApiError apiErrorWithReasonCode:LcApiError_INTERNAL reason:error.localizedDescription];
    errorHandler(requestData, apiError);
  }];
}

@end
